//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


//----------------------------------------------------------------------------------------
// patterns & practices - Smart Client Software Factory - Guidance Package
//
// This file was generated by the "Add View" recipe.
//
// A presenter calls methods of a view to update the information that the view displays. 
// The view exposes its methods through an interface definition, and the presenter contains
// a reference to the view interface. This allows you to test the presenter with different 
// implementations of a view (for example, a mock view).
//
// For more information see:
// ms-help://MS.VSCC.v80/MS.VSIPCC.v80/ms.practices.scsf.2007may/SCSF/html/02-09-010-ModelViewPresenter_MVP.htm
//
// Latest version of this Guidance Package: http://go.microsoft.com/fwlink/?LinkId=62182
//----------------------------------------------------------------------------------------

using System;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeUI;
using LitwareHR.Infrastructure.Interface;
using LitwareHR.PublicApp.WinUX.Services;
using System.Data;
using Microsoft.Practices.CompositeUI.Utility;
using LitwareHR.Recruiting.Contract;
using Microsoft.Practices.CompositeUI.EventBroker;
using LitwareHR.Infrastructure.Interface.Constants;
using System.Globalization;
using Microsoft.Practices.SmartClient.ConnectionMonitor;

namespace LitwareHR.PublicApp.WinUX
{
    public partial class CandidatesViewPresenter : Presenter<ICandidatesView>
    {
        string silverlightUrl = "http://silverlight.services.live.com/invoke/{0}/{1}/iframe.html";
        RecruitingService recruitingService;
        ConnectionMonitor connectionMonitor;

        [InjectionConstructor]
        public CandidatesViewPresenter([ServiceDependency] RecruitingService recruitingService
                                       , [ServiceDependency] ConnectionMonitor connectionMonitor)
        {
            this.recruitingService = recruitingService;
            this.connectionMonitor = connectionMonitor;
        }
        /// <summary>
        /// This method is a placeholder that will be called by the view when it has been loaded.
        /// </summary>
        public override void OnViewReady()
        {
            base.OnViewReady();
            View.LoadResources();
            View.SetUpControls();
            OnShowCandidates();
        }

        /// <summary>
        /// Close the view
        /// </summary>
        public void OnCloseView()
        {
            base.CloseView();
            WorkItem.SmartParts.Remove(View);
            if (View is IDisposable)
                ((IDisposable)View).Dispose();
        }

        public void OnShowCandidates()
        {
            DataTable candidates = null;
            if (connectionMonitor.IsConnected)
            {
                candidates = recruitingService.GetRecruitingWorkFlowList();
                candidates.Columns.Add("Position");
                foreach (DataRow row in candidates.Rows)
                {
                    row["Position"] = recruitingService.GetPositionName(new Guid(row["PositionId"].ToString()));
                }
            }
            View.ShowCandidates(candidates);
        }


        internal void OnCandidateSelected(object selectedCandidate)
        {
            if (!connectionMonitor.IsConnected)
            {
                View.ShowOfflinePanel();
                return;
            }

            DataRowView rowView = selectedCandidate as DataRowView;

            if (rowView == null)
                return;

            Guid resumeId = new Guid(rowView.Row["ResumeId"].ToString());

            SilverlightAccount slAccount = recruitingService.GetSilverlightAccount();
            Resume resume = recruitingService.GetResume(resumeId);
            Uri resumeVideoUri = null;            

            if (slAccount != null)
            {

                if (resume.VideoUploadState == VideoUploadState.Available)
                {
                    string silverlightAppName = resume.Id.ToString().Replace("-", String.Empty);

                    string resumeVideoUrl = String.Format(CultureInfo.InvariantCulture
                                                         , silverlightUrl
                                                         , slAccount.AccountId
                                                         , silverlightAppName);

                    resumeVideoUri = new Uri(resumeVideoUrl);

                    View.ShowWebBrowser();
                }
                else
                {
                    string msg = string.Empty;
                    switch (resume.VideoUploadState)
                    {
                        case VideoUploadState.Error:
                            msg = "Error In Video Upload Process";
                            break;
                        case VideoUploadState.NoExists:
                            msg = "No Video Available";
                            break;
                        case VideoUploadState.Uploading:
                            msg = "Video Upload in Progress";
                            break;  
                    }
                    View.ShowNoVideoAvailableMessage(msg);
                }
            }
            else
            {
                View.HideWebBrowser();
            }
           
            View.ShowResume(resume, resumeVideoUri);
        }

        [EventSubscription(EventTopicNames.MetaModelUpdating, ThreadOption.UserInterface)]
        public void OnMetaModelUpdating(object sender, EventArgs eventArgs)
        {
            View.StartSyncAnimation();
        }

        [EventSubscription(EventTopicNames.MetaModelUpdated, ThreadOption.UserInterface)]
        public void OnMetaModelUpdated(object sender, EventArgs eventArgs)
        {
            View.NotifySchemaChanges();
            View.EndSyncAnimation();
        }

        [EventSubscription(EventTopicNames.DataSynchronizing, ThreadOption.UserInterface)]
        public void OnDataSynchronizing(object sender, EventArgs eventArgs)
        {
            View.StartSyncAnimation();
        }

        [EventSubscription(EventTopicNames.DataSynchronized, ThreadOption.UserInterface)]
        public void OnDataSynchronized(object sender, EventArgs eventArgs)
        {
            OnShowCandidates();
            View.EndSyncAnimation();
        }
    }
}
